//1，未执行；2，运行中；3，成功；4，失败；
var AssemblyLine = {
baseInfoLayer:function(obj,okFun){
	if(window.baseInfoLayerIndex){
		return false;
	}
	
	window.baseInfoLayerIndex = layer.open({
		title:"基本信息",
		type: 1,
		shade:0,
		move:false,
		offset: ['40px', $(window).width()-510],
		content: $('#baseInfo_layer_wrapper'),
		area: ['500px', 'auto'],
		btn: ['确定', '取消'],
		success: function(layero, index){
		  		//$('.layui-layer-content [name="region_select"]').selectpicker();
		  		//$('.layui-layer-content [name="env_select"]').selectpicker();
		},
		end:function(){
			window.baseInfoLayerIndex = null;
		},
		yes: function(index, layero){
			var lineName = $('#line-name').val();
			var lineDesc = $('#line-desc').val();
			
			//显示到页面
			$('.line-name').text(lineName);
			$('.line-desc').text(lineDesc);
			
	  		if(okFun && typeof(okFun) == 'function'){
	  			okFun();
			}
			
		  	layer.close(index);
		}
	});
},
stageLayer:function(obj,fun,okFun){
	if(window.stageLayerIndex || window.jobLayerIndex){
		return false;
	}
	
	window.stageLayerIndex = layer.open({
		title:"阶段",
		type: 1,
		shade:0,
		move:false,
		offset: ['40px', $(window).width()-510],
		content: $('#stage_layer_wrapper'),
		area: ['500px', 'auto'],
	  	btn: ['确定', '取消'],
	  	success: function(layero, index){
	  		//$('.layui-layer-content [name="region_select"]').selectpicker();
	  		//$('.layui-layer-content [name="env_select"]').selectpicker();
	  	},
		end:function(){
			window.stageLayerIndex = null;
		},
	  	yes: function(index, layero){
	  		var sname = $('#stage-name').val();
	  		if(!sname){
	  			toast.info('请输入阶段名称！','温馨提示');
	  			return false;
	  		}
			//保存阶段
	  		if(okFun && typeof(okFun) == 'function'){
	  			okFun(sname);
			}
	  		layer.close(index);
	  	},
	  	btn2: function(index, layero){
	    	AssemblyLine.closeConform('内容尚未保存，确定取消阶段编辑？',function(){
	    		$(obj).slideUp(200,function(){
	    			$(obj).remove()
	    		});
	    		layer.close(index);
	    	});
	    	
	    	return false;
	    },
	    cancel: function(index){
	    	AssemblyLine.closeConform('内容尚未保存，确定取消阶段编辑？',function(){
	    		$(obj).slideUp(200,function(){
	    			$(obj).remove()
	    		});
	    		layer.close(index);
	    	});
	    	
	    	return false;
	    }
	});
	
	if(fun && typeof(fun) == 'function'){
		fun();
	}
	
}
,jobLayer:function(acttype,obj,fun,okFun){
	//窗口是否已经存在
	if(window.jobLayerIndex || window.stageLayerIndex){
		return false;
	}
	window.jobLayerIndex = layer.open({
		title:"任务",
		type: 1,
		shade:0,
		move:false,
		offset: ['40px', $(window).width()-440],
		content: $('#job_layer_wrapper'),
		area: ['420px', 'auto'],
	  	btn: ['确定', '取消'],
	  	success: function(layero, index){
	  		//$('.layui-layer-content [name="region_select"]').selectpicker();
	  		//$('.layui-layer-content [name="env_select"]').selectpicker();
	  		$('.layui-layer-content').css({height:"auto",'max-height':$(window).height()-100});
	  	},
		end:function(){
    		//清理表单
    		$('#jobForm')[0].reset();
    		$('#jobForm').find('.change-wrap').addClass('hidden');
			window.jobLayerIndex = null;
		},
	  	yes: function(index, layero){
	  		//保存任务事件
	  		var tname = $('[name="jobName"]').val();
	  		if(!tname){
	  			toast.info('请输入任务名称！','温馨提示');
	  			return false;
	  		}
	  		
	  		var jobData = format_form_data($('#jobForm').serializeArray());
	  		
	  		if(okFun && typeof(okFun) == 'function'){
	  			okFun(jobData);
			}
	  		layer.close(index);
	  	},
	  	btn2: function(index, layero){
	    	AssemblyLine.closeConform('内容尚未保存，确定取消任务编辑？',function(){
//	    		$(obj).fadeOut(200,function(){
//	    			$(obj).remove()
//	    		});
	    		if(acttype == 'add') AssemblyLine.jobRemove(obj);
	    		layer.close(index);
	    	});
	    	
	    	return false;
	    },
	    cancel: function(index){
	    	AssemblyLine.closeConform('内容尚未保存，确定取消任务编辑？',function(){
//	    		$(obj).fadeOut(200,function(){
//	    			$(obj).remove()
//	    		});
	    		if(acttype == 'add') AssemblyLine.jobRemove(obj);
	    		layer.close(index);
	    	});
	    	
	    	return false;
	    }
	});

	if(fun && typeof(fun) == 'function'){
		fun();
	}
}
//任务删除统一方法
,jobRemove:function($obj){
	//debugger
	$entryObj = $obj;
	var $itemsWrap = $obj.parents('.plan-item-wrap');
	if($itemsWrap.find('.plan-item').length == 1){
		$entryObj = $itemsWrap;
		$($itemsWrap.next('.plan-item-wrap')).remove();
	}
	$entryObj.fadeOut(400,function(){
		$entryObj.remove();
	});
}
,closeConform:function(title,fun){
	layer.confirm(title, {icon: 3, title:'温馨提示'}, function(index){
		if(fun && typeof(fun) == 'function'){
			fun();
		}
		layer.close(index);
	});
}
,jobConfigureReview:function(data){
	//任务编辑表单内容复现
	$('#jobForm [name="jobName"]').val(data.jobName);
	$('#jobForm select[name="jobType"] option[value="'+data.jobType+'"]').attr('selected','selected');
	$('#jobForm .jobType-'+data.jobType).removeClass('hidden');
	
	var keys = Object.keys(data);
	var klen = keys.length;
	for(var i = 0;i<klen;i++){
		var $ele = $('#jobForm .'+data.jobType+' [name="'+keys[i]+'"]');
		if($ele.length){
			//console.info($ele[0].tagName);
			if($ele[0].tagName == 'INPUT'){
				$('#jobForm [name="'+keys[i]+'"]').val(data[keys[i]]);
			}
			if($ele[0].tagName == 'SELECT'){
				$('#jobForm select[name="'+keys[i]+'"] option[value="'+data[keys[i]]+'"]').attr('selected','selected');
			}
		}
		
	}
	
},
// resetSort:function(){
// 	//阶段拖拽，调整对应右侧导航顺序
// 	var newScrollpy = '';
// 	$('.timeline-wrap').each(function(){
// 		var _self = this;
// 		//console.info(_self.outerHTML);
// 		var title = $(_self).find('.stage-name').text();
// 		var id = _self.id;
// 		$('#scrollspy-control li').each(function(idx,ev){
			
// 			if(idx == 0){
// 				newScrollpy += newScrollpy == '' ? ev.outerHTML : '';
// 				return true;
// 			}
// 			if($(ev).find('a[href="#'+id+'"]').length){
// 				newScrollpy += ev.outerHTML;
// 			}
// 		});
// 	});
	
// 	$('#scrollspy-control ul.nav').html(newScrollpy);
// 	$('body').scrollspy('refresh');
	
// },
getAllData: function(){
	//读取整个流水线数据
	
	//流水线名称
	var pipelineName = $('.line-name').text();
	//流水线备注
	var pipelineDesc = $('.line-desc').text();
	//阶段列表
	var stageList = [];
	//各阶段内数据
	$('.timeline-wrap').each(function(){
		//阶段内任务列表
		var jobList = [];
		var _self = this;
		//阶段名称
		var stageName = $(_self).find('.stage-name').text();
		//同时进行的任务
		$(_self).find('.plan-item-list>.plan-item-wrap').each(function(index,item){
			//是否包含任务
			if($(item).find('.plan-item').length > 0){
				var jobEleList = $(item).find('.plan-item');
				$(jobEleList).each(function(tidx,job){
					//任务设置参数
					var jobData = $(job).data('jobData');
//					console.log("jobData:"+JSON.stringify(jobData));
					//并行任务归类
					jobData.parallelIndex = index;
					jobList.push(jobData);
				});
			}
		});
		stageList.push({"stageName":stageName,"jobList":jobList});
		
	});
	var result = {"pipelineName":pipelineName,"pipelineDesc":pipelineDesc,"stageList":stageList};
//	console.info("result:"+result);
	return result;
	
},

//重组页面内容
reviewPipeLineInfo: function(pipelineId,pipelineVersion,flag){
	var param = {pipelineId:pipelineId};
	if(pipelineVersion) param.pipelineVersion = pipelineVersion;
	//清理旧数据内容
	$('.pipeline .timeline-wrap').remove();

	
		
	//查询流水线信息
//		$.post(path+"/getPipeline.do",param,function(res){
//	var res = {"sysId":"001","pipelineId":"20595a0584e14fefbf267570e5a6c23b","pipelineName":"0001","pipelineDesc":"流水线1","stageList":[{"stageId":"stageId01","stageName":"1111","jobList":[{"jobName":"111101","jobType":"1","codeSources":"gitlab","codeGitConfigure":"git配置1","codeGitProjectName":"","codeGitBranch":"","codeSvnConfigure":"svn配置1","buildSystem":"jenkins","buildAssemblingJobType":"jobtype1","buildAssemblingJobName":"job1","JenkinsConfigure":"1","jenkinsView":"1","deploySystem":"cfe","deployCFEPodType":"1","deployCFEAppName":"","deployCFERelease":"","testSystem":"jenkins","testJenkinsConfigure":"1","testJenkinsView":"1","parallelIndex":1},{"jobName":"111102","jobType":"1","codeSources":"gitlab","codeGitConfigure":"git配置1","codeGitProjectName":"","codeGitBranch":"","codeSvnConfigure":"svn配置1","buildSystem":"jenkins","buildAssemblingJobType":"jobtype1","buildAssemblingJobName":"job1","JenkinsConfigure":"1","jenkinsView":"1","deploySystem":"cfe","deployCFEPodType":"1","deployCFEAppName":"","deployCFERelease":"","testSystem":"jenkins","testJenkinsConfigure":"1","testJenkinsView":"1","parallelIndex":1}]},
//		{"stageId":"stageId02","stageName":"2222","jobList":[{"jobName":"222201","jobType":"2","codeSources":"gitlab","codeGitConfigure":"git配置1","codeGitProjectName":"","codeGitBranch":"","codeSvnConfigure":"svn配置1","buildSystem":"jenkins","buildAssemblingJobType":"jobtype1","buildAssemblingJobName":"job1","JenkinsConfigure":"1","jenkinsView":"1","deploySystem":"cfe","deployCFEPodType":"1","deployCFEAppName":"","deployCFERelease":"","testSystem":"jenkins","testJenkinsConfigure":"1","testJenkinsView":"1","parallelIndex":1},{"jobName":"222202","jobType":"2","codeSources":"gitlab","codeGitConfigure":"git配置1","codeGitProjectName":"","codeGitBranch":"","codeSvnConfigure":"svn配置1","buildSystem":"jenkins","buildAssemblingJobType":"jobtype1","buildAssemblingJobName":"job1","JenkinsConfigure":"1","jenkinsView":"1","deploySystem":"cfe","deployCFEPodType":"1","deployCFEAppName":"","deployCFERelease":"","testSystem":"jenkins","testJenkinsConfigure":"1","testJenkinsView":"1","parallelIndex":1}]}]}
			var res = "";
			if(flag == 1 && globalData !=""){
//				alert(1111);
//				console.log("globalData====: "+JSON.stringify(globalData));
				res = globalData;
			}else{
//				alert(2222);
				res = {"pipelineId":"20595a0584e14fefbf267570e5a6c23b","pipelineName":"0002","pipelineDesc":"流水线2","stageList":[
					{"stageId":"stageId01","stageName":"11","jobList":[
						{"jobName":"11011","parallelIndex":1},
						{"jobName":"11012","parallelIndex":1},
						{"jobName":"11021","parallelIndex":3},
						{"jobName":"11022","parallelIndex":3}]
					},
					{"stageId":"stageId02","stageName":"22","jobList":[
						{"jobName":"22011","parallelIndex":1},
						{"jobName":"22012","parallelIndex":1},
						{"jobName":"22021","parallelIndex":3},
						{"jobName":"22022","parallelIndex":3}]
					}]
				};
			}			
	
//	var res = {"pipelineId":"20595a0584e14fefbf267570e5a6c23b","pipelineName":"00001","pipelineDesc":"流水线1","stageList":[{"stageName":"Source","jobList":[{"jobName":"11","parallelIndex":1}]},{"stageName":"Build","jobList":[{"jobName":"22","parallelIndex":1}]},{"stageName":"Deploy","jobList":[{"jobName":"33","parallelIndex":1}]}]};
				
//		console.info(res);
		AssemblyLine.reviewStaticInfo(res);
//		});
},
//重组右侧脚本
reviewCodeInfo: function(flag){
	$.ajax({
	    type : "post",
	    async: false,
	    url : './home/getPipeline.do',//找到controller里相应的方法
	   
	    success : function(data) {
	    	var data0 = decodeURI(data);
	    	$('#pipeline').val(data0);
//	    	debugger;
	    	if(flag == 1){
//	    		alert(3333);
	    		globalData = AssemblyLine.pipelineNodeInfo(data0);
	    	}
	    	
	    
//		    	map['key1'] = 1;
    	},
	    error : function(data) {
//	    	layer.alert('操作失败');
	    }
	   });
	
},
//页面重组方法封装
reviewStaticInfo: function(res){
	if(res && res.pipelineId){
//		alert(1111);
//		$('[name="pipelineVersion"]').val(res.pipelineVersion);
	$('.line-name').text(res.pipelineName);
	$('.line-desc').text(res.pipelineDesc);
	$('#scrollspy-control .nav').html('<li class=""><a href="#one">基本信息</a></li>');
	
	var stageList = res.stageList;
	if(stageList){
		//var stageLen = stageList.length;
		$.each(stageList,function(idx,stage){
			var $stageHtml = $('<div id="'+stage.stageId+'" class="timeline-wrap ">\n' +
				    '    <div class="timeline-entry timeline-source">\n' +
				    '      <div class="timeline-stat">\n' +
				    '        <div class="timeline-icon">\n' +
				    '          <i class="fa fa-file-code-o icon-2x"></i>\n' +
				    '        </div>\n' +
				    '      </div>\n' +
				    '      <div class="timeline-label">\n' +
				    '        <div class="panel">\n' +
				    '          <div class="panel-heading timeline-sort-drag">\n' +
				    '              <div class="panel-control">\n' +
					'					<a class="btn btn-link btn-lg" >\n' +
					'				    	<i class="fa fa-pencil"></i>\n' +
					'				    </a>\n' +
					'					<a class="btn btn-link btn-lg" >\n' +
					'				         <i class="fa fa-trash"></i>\n' + 
					'				    </a>\n' +
					'				</div>\n' +
				    '            <h3 class="panel-title stage-name">'+stage.stageName+'</h3>\n' +
				    '          </div>\n' +
				    '          <div class="panel-body plan-item-list connectedSortable">\n'+
				    '				<div class="plan-item-wrap">\n' +
					'					<a class="plan-item-add plan-wrap-add">\n' +
					'						<i class="cds-icon-add"></i> \n' +
					'						<span>任务</span>\n' +
					'					</a>\n' +
					'				</div>\n'+
				    '          </div>\n' +
				    '        </div>\n' +
				    '      </div>\n' +
				    '    </div>\n' +
				    
				    '		<div class="timeline-entry timeline-add">\n' +
					'			<div class="timeline-stat">\n' +
					'				<div class="timeline-icon">\n' +
					'					<i class="fa fa-plus-square-o icon-2x"></i>\n' +
					'				</div>\n' +
					//'				<div class="timeline-time">基本信息</div>\n' +
					'			</div>\n' +
					'			<div class="timeline-label">\n' +
					'				<button class="btn btn-block"><i class="fa fa-plus"></i> 阶段</button>\n' +
					'			</div>\n' +
					'		</div>\n' +
				    '  </div>');
			$stageHtml.find( ".panel>.panel-body" ).sortable({
				items: ".plan-item",
				handle:".panel-heading",
				connectWith: ".plan-item-wrap",
				distance: 15,//鼠标移动一定距离才响应
				placeholder: "ui-state-highlight-item"
			});

		    //把阶段区域插入页面
			$('.pipeline').append($stageHtml);
			//添加右侧导航
			$('#scrollspy-control .nav').append('<li class=""><a href="#'+stage.stageId+'">'+stage.stageName+'</a></li>');

	    	var $itemList = $stageHtml.find('.plan-item-list');
			
	    	var jobList = stage.jobList;
		    if(jobList){
		    	var jobHtml = '',jobIndex,$jobWrap;
		    	//任务列表
		    	$.each(jobList,function(jobidx,job){
		    		//debugger
		    		//$jobWrap = !$jobWrap ? $('<div id="'+job.jobIndex+'" class="plan-item-wrap row"></div>') : $jobWrap;
		    		
		    		if(!jobIndex){
		    			$itemList.append('<div id="'+idx+'-'+job.parallelIndex+'" class="plan-item-wrap row"></div>');
		    			
		    			jobIndex = job.parallelIndex;
		    		}
		    		
		    		//不是并行任务
		    	    if(job.parallelIndex != jobIndex) {
		    			$itemList.append('				<div class="plan-item-wrap">\n' +
								'					<a class="plan-item-add plan-wrap-add">\n' +
								'						<i class="cds-icon-add"></i> \n' +
								'						<span>任务</span>\n' +
								'					</a>\n' +
								'				</div>\n'+
								'<div id="'+idx+'-'+job.parallelIndex+'" class="plan-item-wrap row"></div>');
		    	    	//上一次的并行，插入添加任务按钮到末尾
		    	    	$('#'+idx+'-'+jobIndex).append('<a class="plan-item-add">\n'+
			    	        '<i class="cds-icon-add"></i>\n'+
			    	        '<span>任务</span>\n'+
			    	      '</a></div>\n');
		    	    	
		    	    	jobIndex = job.parallelIndex;
		    	    }
		    	    
		    	    
		    	    var $jobItem = $('    <div class="panel plan-item col-lg-2">\n' +
				    	    '        <div class="panel-heading">\n' +
				    	    '            <div class="panel-control" style="padding: 0px!important;">\n' +
				    	    '                <a class="btn btn-link"><i class="fa fa-pencil"></i> </a>\n' +
				    	    '                <a class="btn btn-link"><i class="fa fa-trash"></i> </a>\n' +
				    	    '            </div>\n' +
				    	    '            <h3 class="panel-title" title="'+job.jobName+'">'+job.jobName+'</h3>\n' +
				    	    '        </div>\n' +
				    	    '        <div class="panel-body"></div>\n' +
				    	    '    </div>').data("jobData",job);
		    	    //['+job.jobType+']
		    	    $('#'+idx+'-'+job.parallelIndex).append($jobItem);
		    	    
		    	    $jobItem = null;
		    	    
		    	});
		    	//console.info($('#'+idx+'-'+jobIndex));
		    	//最后一个任务后加上添加任务按钮
		    	$('#'+idx+'-'+jobIndex).append('<a class="plan-item-add">\n'+
		    	        '<i class="cds-icon-add"></i>\n'+
		    	        '<span>任务</span>\n'+
		    	      '</a></div>\n');
		    	
		    }
			$itemList.append('			<div class="plan-item-wrap">\n' +
					'				<a class="plan-item-add plan-wrap-add">\n' +
					'					<i class="cds-icon-add"></i> \n' +
					'					<span>任务</span>\n' +
					'				</a>\n' +
					'			</div>\n');
		});
		

		
	}
}
},

//将获得的脚本进行解析
pipelineNodeInfo: function(pipelineNode){
	var dataList = [];
	var nodeStr = pipelineNode.split("node");
	var nodeNum=nodeStr.length-1;
//	console.log("nodeNum: " + nodeNum);
	
	for(var i = 1; i <= nodeNum; i++){
		var stageIndex = nodeStr[i].indexOf("stage");
		var index0 = nodeStr[i].indexOf("-");
//		console.log("stageIndex:"+stageIndex);
//		console.log("index0:"+index0);
		var stageName = nodeStr[i].substring(stageIndex+7,index0);
//		console.log("stageName: "+stageName);
		var stageStr = nodeStr[i].split("stage");
    	var stageNum=stageStr.length-1;
//    	console.log("stageNum: " + stageNum);
    	var jobNameList = [];
    	for(var j = 1; j <= stageNum; j++){
    		if(stageStr[j].indexOf("parallel") == -1){
    			var stage_jobList = stageStr[j].split("build job");
    			var jobList = stage_jobList[1].split("'");
    			var jobName = jobList[1];
//    			console.log("jobName1111:"+jobName);
    			jobNameList.push(jobName);
    		}else{
    			var stage_paraList = stageStr[j].split(",");
    			var jobParallel = "";
    			for(var k = 0; k < stage_paraList.length; k++){
    				var stage_jobList = stage_paraList[k].split("build job");
	    			var jobList = stage_jobList[1].split("'");
	    			var jobName = jobList[1];
	    			jobParallel += jobParallel==""?"":"=";
	    			jobParallel += jobName;
    			}
//    			console.log("jobParallel:"+jobParallel);
    			jobNameList.push(jobParallel);
    		}
    	
    	}
//    	console.log("jobNameList:"+jobNameList);
    	dataList.push({"stageName" : stageName, "jobNameList" : jobNameList});
	
	}
//	console.log("data: " + JSON.stringify(dataList));
	
	var newStageList = [];
	$(dataList).each(function(index,data){
		var newJobList = [];
		$(data.jobNameList).each(function(paraIdx,paraJob){
			if(paraJob.indexOf("=") == -1){
				newJobList.push({"jobName":paraJob,"parallelIndex":2*paraIdx+1});					
			}else{
				var jobStr = paraJob.split("=");
				$(jobStr).each(function(i,jobSub){
					newJobList.push({"jobName":jobSub,"parallelIndex":2*paraIdx+1});	
				});		
			}
		});		
		newStageList.push({"stageId":"stageId0" + index+1,"stageName":data.stageName,"jobList":newJobList});
		
	});

	var res = {"pipelineId":"20595a0584e14fefbf267570e5a6c23b","pipelineName":"0002","pipelineDesc":"流水线2","stageList":newStageList}
	
	
	
	return res;
},


}
//重编表单数据
function format_form_data(data){
var ne = {};
$.each(data, function(i, field){
	ne[field.name] = field.value;
});
return ne;
}